from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout,CMakeDeps
from conan.tools.files import copy, get,chdir
from conan.tools.gnu import Autotools, AutotoolsToolchain
from conan.tools.scm import Git
import os

class FmtRecipe(ConanFile):
    name = "libzip"  # 库的名称
    version = "1.8.0"  # 假设使用此版本
    user = "thirdparty"
    channel = "stable"  # stable development
    license = "BSD-3-Clause"  # libzip 库的许可证
    author = "Dieter Baron and Thomas Klausner"  # libzip 库的维护者
    url = "https://libzip.org/"  # libzip 库的官网地址
    description = "A C library for reading, creating, and modifying zip archives."  # 库的描述
    topics = ("zip", "compression", "archive", "libzip")  # 相关主题
    settings = "os", "compiler", "build_type", "arch"  # 包的配置
    options = {"shared": [True, False], "fPIC": [True, False]}  # 可选项配置
    default_options = {"shared": False, "fPIC": True}  # 默认选项设置
    # exports_sources = "expat/*" 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.build_mode = "cmake"   
        self.work_dir = ""
    def source(self):# two step
 
        # Step 1: Clone the repository
        git = Git(self)
        git.clone("ssh://git@172.16.57.28:2289/ads/thirdparty/libzip.git", target=self.source_folder)

        # Step 2: Check if the .git folder exists to ensure the repository is cloned correctly
        if not os.path.exists(os.path.join(self.source_folder, ".git")):
            raise ConanException("Git repository was not cloned successfully.")

        # Step 3: Switch to the desired branch (or tag) after cloning
        with chdir(self, self.source_folder):  # Ensure we're in the correct directory
            git.checkout("release_1.8.0")

        self.output.info("source ：self.source_folder  = " + self.source_folder)
        # 如果cmakelist.txt在subfolder文件夹下,则需要将文件夹移动到source_folder下
#        self.work_dir = os.path.join(self.source_folder, "subfolder")
    def requirements(self):
        self.requires("zlib/1.2.11@thirdparty/stable")

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC # Windows does not require -fPIC flag

    def layout(self):# first step   
        cmake_layout(self)
        self.output.info("layout ： self.folders.source = " + self.folders.source)    
        #self.folders.source = os.path.join(self.folders.source, "expat")

    def generate(self):# third step
        self.detect_build_system()
        self.output.info("generate pwd = " + os.getcwd())
        if self.build_mode == "cmake":
            tc = CMakeToolchain(self)
            tc.variables["BUILD_TOOLS"] = "OFF"  # 在这里配置变量
            tc.variables["BUILD_EXAMPLES"] = "OFF"  # 在这里配置变量
            tc.variables["BUILD_DOC"] = "OFF"  # 在这里配置变量
            tc.variables["BUILD_REGRESS"] = "OFF"  # 在这里配置变量
            tc.variables["ENABLE_BZIP2"] = "OFF"  # 在这里配置变量
            tc.variables["ENABLE_LZMA"] = "OFF"  # 在这里配置变量
            tc.variables["ENABLE_ZSTD"] = "OFF"  # 在这里配置变量
#            tc.variables["WITH_LIBBSD"] = "OFF"  # 在这里配置变量
            tc.generate()
            deps = CMakeDeps(self)
            deps.generate()
        elif self.build_mode == "autotools":
            tc = AutotoolsToolchain(self)
            tc.generate()
        else:
            raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")

    def build(self):
        self.output.info(" build pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            self.output.info("执行 CMake 构建流程")
            cmake = CMake(self)    
            cmake.configure()
            cmake.build()
        elif self.build_mode == "autotools":    
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.configure(args=["--prefix={}".format(self.package_folder)])
                autotools.make()
    def package(self):
        self.output.info(" package pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            cmake = CMake(self)
            cmake.install()
        elif self.build_mode == "autotools":  
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.install()
            
    def package_info(self):
        # 为 CMake 提供 ZLIB 库文件名
        self.cpp_info.libs = ["libzip"]

        # 使用 set_property 设置 cmake_find_package 和 cmake_find_package_multi 的名称
        self.cpp_info.set_property("cmake_find_package", "libzip")
        self.cpp_info.set_property("cmake_find_package_multi", "libzip")

        # 如果有组件，确保为组件也设置属性
        self.cpp_info.components["libzip"].set_property("cmake_find_package", "libzip")
        self.cpp_info.components["libzip"].set_property("cmake_find_package_multi", "libzip")
        
        self.cpp_info.requires = ["zlib::zlib"]

        # 设置 CMake 的目标名称
        self.cpp_info.set_property("cmake_target_name", "libzip::libzip")
        
        # 设置 CMake 配置的文件名
        self.cpp_info.set_property("cmake_file_name", "libzip")
    def detect_build_system(self):
        cmake_file_path = os.path.join(self.source_folder, "CMakeLists.txt")
        
        if os.path.exists(cmake_file_path):
            self.output.info("CMakeLists.txt exists: Yes")
        elif os.path.exists(os.path.join(self.source_folder, "configure")):
            self.build_mode = "autotools"
            self.output.info("configure exists: Yes")
            # 如果不加权限,configure()方法有可能无法执行
            os.chmod(os.path.join(self.source_folder, "configure"), 0o755)
        else: #目前只处理 CMakeLists.txt 和 configure
            self.output.error("CMakeLists.txt exists: No")
            self.output.error("configure exists: No")
            self.build_mode = str(self.options.usr_mode)
            self.output.info("build_mode = " + self.build_mode)
            # raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")    
